package org.budo.dubbo.http.client.java.impl;

import org.budo.dubbo.http.client.java.RequestContext;
import org.budo.dubbo.http.client.java.ResponseHandler;
import org.budo.dubbo.http.client.java.exception.ApiErrorException;

/**
 * @author lmw-2
 */
public abstract class AbstractResponseHandler implements ResponseHandler {
    @Override
    public Object handleResponse(RequestContext requestContext) {
        if (null != requestContext.getException()) {
            this.handleException(requestContext);
            return null;
        }

        return this.handleResponseBody(requestContext);
    }

    private void handleException(RequestContext requestContext) {
        Throwable exception = requestContext.getException();
        ApiErrorException error = exception instanceof ApiErrorException ? (ApiErrorException) exception : new ApiErrorException(exception);
        if (requestContext.getAsync()) {
            requestContext.getApiCallback().fail(error, requestContext); // 异常
        } else {
            throw error;
        }
    }

    public abstract Object handleResponseBody(RequestContext requestContext);
}
